/*
 * diarioGeneral.java
 *
 * Created on 2 de septiembre de 2008, 03:03 PM
 */

package administrador;
import java.text.ParseException;
import java.util.Calendar;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author  Jorge
 */
public class diarioGeneral extends javax.swing.JFrame {

    /** Creates new form diarioGeneral */
    Conexion conexion;
    String operacion;
    calendario.JCalendar jCalendar = null;
    String fecha=null;
    javax.swing.JTable tabla;
    javax.swing.JScrollPane js;
    public diarioGeneral(Conexion conexion, String operacion) {
        this.conexion=conexion;
        this.operacion=operacion;
        initComponents();
        setVisible(true);
        jCalendar = new calendario.JCalendar(this, "Calendario", true);
        if(operacion.equals("Nuevo")){
            setTitle("Insertar Nuevo Diario");
            txt_Codigo.setText(String.valueOf(ultimoCodigo()));
            fecha=new java.sql.Date(System.currentTimeMillis()).toString();
            //txt_fecha.setText(fecha);
        }
        actualizaTabla();
    }
    java.sql.ResultSet respuesta=null;
    public void actualizaTabla(){
        respuesta=conexion.consultarBase("Select cod_diario as Codigo,desc_diario as Descripción,fecha_diario as Fecha  from diario");
        muestroTabla(respuesta);
    }
    public int ultimoCodigo(){
        int maxCodigo=0;
        try{
            java.sql.ResultSet r=conexion.consultarBase("select max(cod_diario) from diario");
            r.next();
            int numero=r.getInt(1);
            maxCodigo=numero+1;
        }catch(SQLException sql){}
        return maxCodigo;
    }
    public String lastYear(){
        String ultimoYear="";
        try{
            java.sql.ResultSet r=conexion.consultarBase("select max(year(fecha_diario)) from diario");
            int filas=conexion.obtenerFilas(r);
            if(filas==0){
            ultimoYear="";
            }else{
            r.next();
            ultimoYear=r.getString(1);
            }
            
            
        }catch(SQLException sql){}
        return ultimoYear;
    }
    java.sql.Date fecha1=null;
    java.sql.Date fecha2=null;
    public void sacarFecha(int opcion) {
        Calendar cDate = jCalendar.getCalendar();
        if (cDate == null) {
            cDate = Calendar.getInstance();
        }
        jCalendar.setCalendar(cDate);
        jCalendar.setVisible(true);
        if (jCalendar.isOkPressed()) {
            if (opcion == 1) {
                fecha1 = new java.sql.Date(jCalendar.getDate().getTime());
                txt_fecha.setText(fecha1.toString());
            }
            jCalendar.setVisible(false);
        }
    }
    public void Insertar(){
        conexion.insertarDatos("insert into diario (desc_diario,fecha_diario) values('"+area_Desc.getText()+"','"+txt_fecha.getText()+"')");
        recargar();
        actualizaTabla();
    }
    public void recargar(){
        txt_Codigo.setText(String.valueOf(ultimoCodigo()));
        area_Desc.setText("");
        txt_fecha.setText(new java.sql.Date(System.currentTimeMillis()).toString());
    }
    public void recargarVacio(){
        txt_Codigo.setText("");
        area_Desc.setText("");
        txt_fecha.setText("");
    }
    public String yearActual(String fechaSelec){
        String year="";
            SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd"); 
            java.util.Date d=null;
            try {
                d = sdf.parse(txt_fecha.getText());
            } catch (ParseException ex) {
                Logger.getLogger(diarioGeneral.class.getName()).log(Level.SEVERE, null, ex);
            }
           Calendar calendario = Calendar.getInstance();
           calendario.setTime(d);
           return String.valueOf(calendario.get(Calendar.YEAR));  //Retorna el 
    }
    public void muestroTabla(java.sql.ResultSet respuesta){
     //Obtengo Filas-Arreglo de Titulos de Columnas
        int filas=conexion.obtenerFilas(respuesta);
        String[] titulosCol=conexion.obtenerColumnas(respuesta);
        //Creo la tabla:
        CrearTabla(filas,titulosCol);
        llenaTabla(respuesta,titulosCol.length,filas);
    }
    public void CrearTabla(int filas,String[] titulos){
        
        int columnas=titulos.length;
        String[][] tabla0=new String[filas][columnas];
       
        tabla= new javax.swing.JTable(tabla0,titulos);
        
        //Aqui le especifico para que la tabla acepte valores doubles e int:
        //--------------------------------------------------------------------
        final boolean[] canEdit = new boolean [columnas];
        for(int p=0;p<columnas;p++){
        canEdit[p]=false;
        }
        tabla.setModel(new javax.swing.table.DefaultTableModel(
            tabla0,titulos  
        ) {
           // boolean[] canEdit = new boolean [] { false, false, false, false};
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        //---------------------------------------------------------------------
                   
        //Le doy el evento del LCick del Mouse:
        tabla.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tablaMouseClicked(evt);
            }
        });
        
        //remuevo el JScroll para que no se monte cuando cree el nuevo:
        //*************************************************************
        try{
        panel_Tabla.remove(js);
        }catch(java.lang.NullPointerException e){}
        //*************************************************************
        //Pongo en la tabla:
            js = new javax.swing.JScrollPane(tabla);
            js.setBounds(0,0,400,150);
            js.setVisible(true);
            panel_Tabla.add(js);
            panel_Tabla.updateUI();
            js.updateUI();
    }
    public void llenaTabla(java.sql.ResultSet r,int columnas,int filas){
        try{
            r.beforeFirst();
            
            int j=0;
            while(r.next()) {
                
                for(int i=0;i<columnas;i++) {
                    
                    Object toma=r.getObject(i+1);
                    //System.out.println("toma valor:"+toma+" * fila:"+j+" * column:"+i);
                    try{
                        tabla.setValueAt(toma,j,i);
                    }catch(java.lang.ArrayStoreException e){
                        System.out.print("Errrrorrr");
                        tabla.setValueAt("null",j,i);
                    }
                }
                
                j++;
            }
        }catch(java.sql.SQLException sqle){
            System.out.println("Error al mostrar los datos");
            System.err.println(sqle);
        }
    }
    private void tablaMouseClicked(java.awt.event.MouseEvent evt) {
        if(this.operacion.equals("Modificar")){
            txt_Codigo.setText(tabla.getValueAt(tabla.getSelectedRow(),0).toString());
            area_Desc.setText(tabla.getValueAt(tabla.getSelectedRow(),1).toString());
            txt_fecha.setText(tabla.getValueAt(tabla.getSelectedRow(),2).toString());
        }
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txt_fecha = new javax.swing.JTextField();
        txt_Codigo = new javax.swing.JTextField();
        btn_fecha = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        area_Desc = new javax.swing.JTextArea();
        jButton3 = new javax.swing.JButton();
        panel_Tabla = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane2.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setName("jPanel1"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(administrador.AdministradorApp.class).getContext().getResourceMap(diarioGeneral.class);
        jLabel1.setText(resourceMap.getString("jLabel1.text")); // NOI18N
        jLabel1.setName("jLabel1"); // NOI18N

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        txt_fecha.setEditable(false);
        txt_fecha.setName("txt_fecha"); // NOI18N
        txt_fecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_fechaActionPerformed(evt);
            }
        });

        txt_Codigo.setEditable(false);
        txt_Codigo.setName("txt_Codigo"); // NOI18N

        btn_fecha.setIcon(resourceMap.getIcon("btn_fecha.icon")); // NOI18N
        btn_fecha.setName("btn_fecha"); // NOI18N
        btn_fecha.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_fechaActionPerformed(evt);
            }
        });

        jLabel3.setName("jLabel3"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        area_Desc.setColumns(20);
        area_Desc.setRows(5);
        area_Desc.setName("area_Desc"); // NOI18N
        jScrollPane1.setViewportView(area_Desc);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 42, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_Codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 208, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(82, 82, 82)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txt_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(btn_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGap(42, 42, 42)
                .addComponent(jLabel3)
                .addGap(117, 117, 117))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_Codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(txt_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btn_fecha, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(16, Short.MAX_VALUE))
        );

        jButton3.setText(resourceMap.getString("jButton3.text")); // NOI18N
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        panel_Tabla.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
        panel_Tabla.setName("panel_Tabla"); // NOI18N
        panel_Tabla.setLayout(new java.awt.BorderLayout());

        jLabel4.setFont(resourceMap.getFont("jLabel4.font")); // NOI18N
        jLabel4.setForeground(resourceMap.getColor("jLabel4.foreground")); // NOI18N
        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(panel_Tabla, javax.swing.GroupLayout.DEFAULT_SIZE, 377, Short.MAX_VALUE))
                    .addComponent(jLabel4))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(panel_Tabla, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 199, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(20, 20, 20))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-703)/2, (screenSize.height-289)/2, 703, 289);
    }// </editor-fold>//GEN-END:initComponents

private void txt_fechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_fechaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_fechaActionPerformed

private void btn_fechaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_fechaActionPerformed
        sacarFecha(1);
}//GEN-LAST:event_btn_fechaActionPerformed

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    if(this.operacion.equals("Nuevo")){
        if(area_Desc.getText().equals("")){
            javax.swing.JOptionPane.showMessageDialog(this,"Debe ingresar la Descripcion","Error",javax.swing.JOptionPane.ERROR_MESSAGE);
        }else{
            if(txt_fecha.getText().equals("")){
                javax.swing.JOptionPane.showMessageDialog(this,"Debe Ingresar la Fecha","Error",javax.swing.JOptionPane.ERROR_MESSAGE);
            }else{
               if(txt_fecha.getText().compareTo(fecha.toString())>=0){
                       if(lastYear().equals("")){
                           Insertar();   
                       }else if(lastYear().compareTo(String.valueOf(yearActual(txt_fecha.getText())))<0){
                                Insertar();
                       } else{
                           javax.swing.JOptionPane.showMessageDialog(this,"El año debe ser mayor al ultimo Ingresado :"+lastYear(),"Error",javax.swing.JOptionPane.ERROR_MESSAGE);
                       }   
               }else{
                   javax.swing.JOptionPane.showMessageDialog(this,"La fecha Ingresada no debe ser menor a la Fecha actual","Error",javax.swing.JOptionPane.ERROR_MESSAGE);
               }
            }
        }
        
    }
    if(this.operacion.equals("Modificar")){
        if(txt_Codigo.getText().equals("")){
            javax.swing.JOptionPane.showMessageDialog(this,"Seleccione el diario a Modificar","Error",javax.swing.JOptionPane.ERROR_MESSAGE);
        }else{
                if(area_Desc.getText().equals("")){
                    javax.swing.JOptionPane.showMessageDialog(this,"Debe ingresar la Descripcion","Error",javax.swing.JOptionPane.ERROR_MESSAGE);
                }else{
                    if(txt_fecha.getText().equals("")){
                        javax.swing.JOptionPane.showMessageDialog(this,"Debe Ingresar la Fecha","Error",javax.swing.JOptionPane.ERROR_MESSAGE);
                    }else{
                        conexion.actualizarBase("update diario set desc_diario='"+area_Desc.getText()+"',fecha_diario='"+txt_fecha.getText()+"' where cod_diario="+txt_Codigo.getText());
                        recargarVacio();
                        actualizaTabla();
                    }
                }

            }
        }
}//GEN-LAST:event_jButton3ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextArea area_Desc;
    private javax.swing.JButton btn_fecha;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable1;
    private javax.swing.JPanel panel_Tabla;
    private javax.swing.JTextField txt_Codigo;
    private javax.swing.JTextField txt_fecha;
    // End of variables declaration//GEN-END:variables

}
